package com.api.oa.config;


import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Component
public class TokenHandler  implements HandlerInterceptor {

    @Value("${appKey}")
    private String appKey;
    //private static final ThreadLocal<Long> partnerDtoThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authentication");
        if (token != null){
            boolean result = JWTUtil.verify(token,appKey.getBytes(StandardCharsets.UTF_8));
            if(result){
                JWT jwt = JWTUtil.parseToken(token);
                JSONObject claimsJson = jwt.getPayload().getClaimsJson();
                UserContext.set("userId",claimsJson.getLong("userId"));
                UserContext.set("role",claimsJson.getLong("role"));
                UserContext.set("insCode",claimsJson.getStr("insCode"));
                return true;
            }else{
               // response.sendError(999,"认证未通过");

            }

        }
        return true;

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // partnerDtoThreadLocal.set(null);
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
